package com.cy.air.postXml.model
{
	import com.cy.air.postXml.ApplicationFacade;
	
	import flash.data.SQLConnection;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import flash.filesystem.File;
	
	import mx.collections.IList;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;

	public class RequestUrlProxy extends Proxy implements IProxy
	{
		public static const NAME:String="sequestUrlProxy";
		
		public function RequestUrlProxy()
		{
			super(NAME);
			initDb();
		}
		
		private var con:SQLConnection;
		
		private var dbOpenStatus:int=0;
		
		private var recordStatus:int=0;
		
		
		public var requesturl:String="";
		
		private function initDb():void{
			var file:File=File.applicationStorageDirectory.resolvePath("postXml.db");
			con=new SQLConnection();
			con.addEventListener(SQLEvent.OPEN,dbOpen);
			con.addEventListener(SQLErrorEvent.ERROR,dbOpenError);
			con.openAsync(file);
		}
		
		public function getUrlFromSqlite():void{
			var sql:String="select url_ from t_url ";
			var sqlstatement:SQLStatement=new SQLStatement();
			sqlstatement.sqlConnection=con;
			sqlstatement.text=sql;
			sqlstatement.addEventListener(SQLEvent.RESULT,getResult);
			sqlstatement.execute();
		}
		
		private function getResult(e:SQLEvent):void{
			var data:Object=e.target.getResult().data;
			if(data!=null){
				requesturl=String(data[0].url_);
				recordStatus=1;
				sendNotification(ApplicationFacade.REQUEST_URL_READY,requesturl);
			}
			
		}
		
		
		public function insertUrlIntoSqlite():void{
			
			
			var sql:String;
			
			if(recordStatus==0){
				sql="insert into t_url (url_) values(:url_) ";
			}else{
				sql="update t_url set url_=:url_ ";
			}
			var sqlstatement:SQLStatement=new SQLStatement();
			sqlstatement.sqlConnection=con;
			sqlstatement.text=sql;
			sqlstatement.parameters[":url_"]=requesturl;
			try{
				sqlstatement.execute();
				recordStatus=1;
			}catch (e:SQLErrorEvent){
				trace(e);
			}
			
			
			
		}
		
		private function dbOpen(e:SQLEvent):void{
			dbOpenStatus=1;
			var sql:String="create table if not exists  t_url(url_ TEXT )";
			var sqlstatement:SQLStatement=new SQLStatement();
			sqlstatement.sqlConnection=con;
			sqlstatement.text=sql;
			sqlstatement.execute();
			
			getUrlFromSqlite();
			
		}
		
		private function dbOpenError(e:SQLErrorEvent):void{
			
		}
	}
}